package zmee.pur.src.report;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.report.FilterInfo;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.report.plugin.AbstractReportFormPlugin;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.util.CollectionUtils;

import java.util.EventObject;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2023/01/12/14:17
 * @Description: 招标情况表；查询维度：招标单位（采购组织）、招标项目、年月
 */
public class PurSituationRptFormPlugin extends AbstractReportFormPlugin {

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        long orgId = RequestContext.get().getOrgId();
        this.getModel().setValue("zmee_org", orgId);
        DynamicObject org = BusinessDataServiceHelper.loadSingle(orgId, "bos_org");
        String orgName = org.getString("name");
        this.getModel().setValue("zmee_title", orgName + "招标（采购）情况表");
    }

    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        super.beforePropertyChanged(e);
        String name = e.getProperty().getName();
        if ("zmee_org".equals(name)) {
            Object newValue = e.getChangeSet()[0].getNewValue();
            if (newValue != null) {
                DynamicObject org = BusinessDataServiceHelper.loadSingle(newValue, "bos_org");
                String orgName = org.getString("name");
                this.getModel().setValue("zmee_title", orgName + "招标（采购）情况表");
            }
        }
    }

    @Override
    public boolean verifyQuery(ReportQueryParam queryParam) {
        FilterInfo filter = queryParam.getFilter();
        DynamicObject org = filter.getDynamicObject("zmee_org");
        if (org == null) {
            this.getView().showTipNotification("请选择招标单位");
            return false;
        }
        return true;
    }

    @Override
    public void processRowData(String gridPK, DynamicObjectCollection rowData, ReportQueryParam queryParam) {
        List<DynamicObject> insertRows = rowData.getInsertRows();
        if (CollectionUtils.isEmpty(insertRows)) {
            return;
        }
        Map<Object, List<DynamicObject>> objMap = insertRows.stream().collect(Collectors.groupingBy(d -> d.get("zmee_month")));
        for (Map.Entry<Object, List<DynamicObject>> item : objMap.entrySet()) {
            List<DynamicObject> value = item.getValue();
            for (int i = 0; i < value.size(); i++) {
                value.get(i).set("zmee_seq", i + 1);
            }
        }
    }

    @Override
    public void setMergeColums(List<String> columns) {
        columns.add("zmee_month");
        super.setMergeColums(columns);
    }
}
